package com.cz.run.config.mvc;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

/**
 * @Description: TODO()
 * @auther:CAIYJ
 * @Date:2018/5/27 12:58
 */
@Configuration
public class CorsConfig {
    private final static List<String> allowedHeaders = new ArrayList<String>() {

        private static final long serialVersionUID = 1L;
        {
            add("Content-Type");
            add("Accept");
            add("X-Requested-With");
            add("remember-me");
            add("token");
            add("authorization");
        }
    };

    private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1 设置访问源地址
        corsConfiguration.setAllowCredentials(true);
        corsConfiguration.setAllowedHeaders(allowedHeaders);// 2 设置访问源请求头
        corsConfiguration.addAllowedMethod("*"); // 3 设置访问源请求方法
        corsConfiguration.addExposedHeader("token"); //设置前端能获取token信息
        corsConfiguration.setMaxAge(3600L);
        return corsConfiguration;
    }

    @Bean
    @Order(1)
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4 对接口配置跨域设置
        return new CorsFilter(source);
    }
}
